<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms :modelValue="formData">
      <!-- 冷却食物日期 -->
      <uni-card title="冷却食物日期" extra="必填*">
        <uni-forms-item>
          <uni-datetime-picker
            type="date"
            :clear-icon="false"
            v-model="formData.date"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 餐段 -->
      <uni-card title="餐段" extra="必填*">
        <uni-forms-item>
          <uni-data-checkbox
            v-model="formData.chanDuan"
            :localdata="chanDuan"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食品名称 -->
      <uni-card title="食品名称" extra="必填*">
        <uni-forms-item>
          <uni-easyinput v-model="formData.foodName" :disabled="isEdit" />
        </uni-forms-item>
      </uni-card>
      <!-- 开始时间 -->
      <uni-card title="开始时间" extra="必填*">
        <uni-forms-item>
          <view
            @click="datesPop = true && !isEdit"
            class="border-solid border-gray-300 flex items-center justify-between rounded h-10 border"
          >
            <text class="float-left ml-3">{{ formData.selectedTime }}</text>
            <uni-icons
              class="float-right font-bold"
              type="arrow-down"
              size="18"
            ></uni-icons>
          </view>
        </uni-forms-item>
      </uni-card>
      <!-- 开始温度/初始温度 -->
      <uni-card title="开始温度/初始温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.startTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.startTemperatureImgs"
            mode="grid"
            @select="uploadStartTemperatureImgs"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 一小时后食品温度 -->
      <uni-card title="1小时后食品温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.afterOneHourTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.afterOneHourTemperatureImgs"
            mode="grid"
            @select="uploadAfterOneHourTemperatureImgs"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 2小时后食品温度 -->
      <uni-card title="2小时后食品温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.afterTwoHourTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.afterTwoHourTemperatureImgs"
            mode="grid"
            @select="uploadAfterTwoHourTemperatureImgs"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 2小时纠正措施 -->
      <uni-card title="纠正措施" extra="必填*">
        <uni-forms-item>
          <uni-data-checkbox
            v-model="formData.towJiuZhenChuoShi"
            :localdata="jiuZhenChuoShi"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 4小时后食品温度 -->
      <uni-card title="4小时后食品温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.afterFourHourTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.afterFourHourTemperatureImgs"
            mode="grid"
            @select="uploadAfterFourHourTemperatureImgs"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 6小时后食品温度 -->
      <uni-card title="6小时后食品温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.afterSixHourTemperature"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.afterSixHourTemperatureImgs"
            mode="grid"
            @select="uploadAfterSixHourTemperatureImgs"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 纠正措施 -->
      <uni-card title="纠正措施" extra="必填*">
        <uni-forms-item>
          <uni-data-checkbox
            v-model="formData.jiuZhenChuoShi"
            :localdata="jiuZhenChuoShi"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 填报人姓名 -->
      <uni-card title="填报人姓名" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.tianBaoRenXinMing"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <uni-card title="评语" v-show="props.id">
        <uni-easyinput v-model="reviewOpinion" />
      </uni-card>
    </uni-forms>
    <button
      @click="submitForm"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
    >
      {{ submitBtnName }}
    </button>
    <ShowConfigComponent
      v-show="!isEdit"
      name="shiWuLengQue"
      @showFormData="showFormData"
    />
  </scroll-view>
  <!-- 开始事件组件 -->
  <Dates
    v-model:selectedTime="formData.selectedTime"
    @timeSelected="handleTimeSelected"
    @popType="datesPop = $event"
    v-if="datesPop"
  />
</template>

<script lang="ts" setup>
/* global BigInt */
import {
  convertToString,
  getTodayDate,
  splitName,
  compareLoadData,
  transformData,
} from '@/utils/utils';
import { ref } from 'vue';
import Dates from '@/components/Dates/Dates.vue';
import type {
  FormDetail,
  returnSubmitData,
  submitTableData,
  tableDate,
} from '@/services/types/write';
import { createTableById, showTableById, submitTable } from '@/services/write';
import { onLoad } from '@dcloudio/uni-app';
import type { RequestMenuIdList } from '@/services/types/review';
import { submitMenuIdList } from '@/services/review';
import { uploadImg } from '@/utils/http';
// 表格提交信息
const formData = ref({
  date: ref(getTodayDate()).value, // 冷却日期 date
  chanDuan: '', // 餐段chanDuan
  foodName: '', // 食物名称foodName
  selectedTime: '', //开始时间selectedTime
  startTemperature: '', // 开始温度startTemperature
  startTemperatureImgs: [] as { url: string; extname: string; name: string }[], // 开始温度图片startTemperatureImgs
  afterOneHourTemperature: '', // 1小时后温度afterOneHourTemperature
  afterOneHourTemperatureImgs: [] as {
    url: string;
    extname: string;
    name: string;
  }[], // 1小时后温度图片afterOneHourTemperatureImgs
  afterTwoHourTemperature: '', // 2小时后温度afterTwoHourTemperature
  afterTwoHourTemperatureImgs: [] as {
    url: string;
    extname: string;
    name: string;
  }[], // 2小时后温度图片afterTwoHourTemperatureImgs
  towJiuZhenChuoShi: '', // 2小时纠正措施
  afterFourHourTemperature: '', // 4小时后温度afterFourHourTemperature
  afterFourHourTemperatureImgs: [] as {
    url: string;
    extname: string;
    name: string;
  }[], // 4小时后温度图片afterFourHourTemperatureImgs
  afterSixHourTemperature: '', // 6小时后温度afterSixHourTemperature
  afterSixHourTemperatureImgs: [] as {
    url: string;
    extname: string;
    name: string;
  }[], // 6小时后温度图片afterSixHourTemperatureImgs
  jiuZhenChuoShi: '', // 纠正措施jiuZhenChuoShi
  tianBaoRenXinMing: '', //填报人姓名
});
//餐段
const chanDuan = [
  {
    text: '早餐',
    value: '早餐',
  },
  {
    text: '午餐',
    value: '午餐',
  },
  {
    text: '晚餐',
    value: '晚餐',
  },
  {
    text: '茶歇',
    value: '茶歇',
  },
  {
    text: '宵夜',
    value: '宵夜',
  },
];
// 纠正措施
const jiuZhenChuoShi = [
  {
    text: 'A. 无需纠正措施',
    value: 'A. 无需纠正措施',
  },
  {
    text: 'B. 再加热至74°C ，仅可再加热一次',
    value: 'B. 再加热至165° F (74° C) ，仅可再加热一次',
  },
  {
    text: 'C. 丢弃',
    value: 'C. 丢弃',
  },
];

// 开始时间显示
const datesPop = ref(false);
// 开始时间组件点击事件
const handleTimeSelected = (time: string) => {
  datesPop.value = false;
  formData.value.selectedTime = time;
};

// 是否可编辑
const isEdit = ref(false);
// 提交按钮名字
const submitBtnName = ref('');
const props = defineProps({
  value: String,
  id: String,
});
// 评语
const reviewOpinion = ref('');
/**
 * 上传函数
 */
const upload = () => {
  // 上传 开始温度图片startTemperatureImgs
  const uploadStartTemperatureImgs = (e: UniHelper.PickerInstance) => {
    uploadImg(e).then((res) => {
      formData.value.startTemperatureImgs.push({
        url: res.url,
        extname: 'jpg',
        name: res.key,
      });
    });
  };
  // 上传 1小时后温度图片afterOneHourTemperatureImgs
  const uploadAfterOneHourTemperatureImgs = (e: UniHelper.PickerInstance) => {
    uploadImg(e).then((res) => {
      formData.value.afterOneHourTemperatureImgs.push({
        url: res.url,
        extname: 'jpg',
        name: res.key,
      });
    });
  };
  // 上传 2小时后温度图片afterTwoHourTemperatureImgs
  const uploadAfterTwoHourTemperatureImgs = (e: UniHelper.PickerInstance) => {
    uploadImg(e).then((res) => {
      formData.value.afterTwoHourTemperatureImgs.push({
        url: res.url,
        extname: 'jpg',
        name: res.key,
      });
    });
  };
  // 上传 4小时后温度图片afterFourHourTemperatureImgs
  const uploadAfterFourHourTemperatureImgs = (e: UniHelper.PickerInstance) => {
    uploadImg(e).then((res) => {
      formData.value.afterFourHourTemperatureImgs.push({
        url: res.url,
        extname: 'jpg',
        name: res.key,
      });
    });
  };
  // 上传 6小时后温度图片afterSixHourTemperatureImgs
  const uploadAfterSixHourTemperatureImgs = (e: UniHelper.PickerInstance) => {
    uploadImg(e).then((res) => {
      formData.value.afterSixHourTemperatureImgs.push({
        url: res.url,
        extname: 'jpg',
        name: res.key,
      });
    });
  };
  return {
    uploadStartTemperatureImgs,
    uploadAfterOneHourTemperatureImgs,
    uploadAfterTwoHourTemperatureImgs,
    uploadAfterFourHourTemperatureImgs,
    uploadAfterSixHourTemperatureImgs,
  };
};
const {
  uploadStartTemperatureImgs,
  uploadAfterOneHourTemperatureImgs,
  uploadAfterTwoHourTemperatureImgs,
  uploadAfterFourHourTemperatureImgs,
  uploadAfterSixHourTemperatureImgs,
} = upload();
/**
 * 表格相关数据
 */
const table = () => {
  const tableData = ref<tableDate[]>([]);
  const reportingFormOperateId = ref('');
  // 如果提交按钮等于提交则创建表格
  const createTable = async () => {
    submitBtnName.value = '提交';
    // 创建表格
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    const res = await createTableById('8286263252886290432');
    reportingFormOperateId.value = res.reportingFormOperateId;
    tableData.value = res.data;
    uni.hideLoading();
  };
  // 提交表格
  const submitNewTable = (
    reportingFormOperateId: string,
    tableData: tableDate[],
  ): submitTableData => {
    const formDetail = transformData(tableData) as FormDetail[];
    // 冷却日期 date
    formDetail[0].componentValue = formData.value.date;
    // 餐段chanDuan
    formDetail[1].options.filter((item) => {
      if (splitName(item.optionTitle) === formData.value.chanDuan) {
        item.selected = true;
      }
    });
    // 食物名称foodName
    formDetail[2].componentValue = formData.value.foodName;
    //开始时间selectedTime
    formDetail[3].componentValue = formData.value.selectedTime;
    // 开始温度startTemperature
    formDetail[4].componentValue = formData.value.startTemperature;
    // 开始温度图片startTemperatureImgs
    if (formData.value.startTemperatureImgs.length) {
      formDetail[5].componentValue = convertToString(
        formData.value.startTemperatureImgs as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 1小时后温度afterOneHourTemperature
    formDetail[6].componentValue = formData.value.afterOneHourTemperature;
    // 1小时后温度图片afterOneHourTemperatureImgs
    if (formData.value.afterOneHourTemperatureImgs.length) {
      formDetail[7].componentValue = convertToString(
        formData.value.afterOneHourTemperatureImgs as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 2小时后温度afterTwoHourTemperature
    formDetail[8].componentValue = formData.value.afterTwoHourTemperature;
    // 2小时后温度图片afterTwoHourTemperatureImgs
    if (formData.value.afterTwoHourTemperatureImgs.length) {
      formDetail[9].componentValue = convertToString(
        formData.value.afterTwoHourTemperatureImgs as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 2小时后纠正措施
    formDetail[10].componentValue = formData.value.towJiuZhenChuoShi;
    formDetail[10].options.filter((item) => {
      if (splitName(item.optionTitle) === formData.value.towJiuZhenChuoShi) {
        item.selected = true;
      }
    });
    // 4小时后温度afterFourHourTemperature
    formDetail[11].componentValue = formData.value.afterFourHourTemperature;
    // 4小时后温度图片afterFourHourTemperatureImgs
    if (formData.value.afterFourHourTemperatureImgs.length) {
      formDetail[12].componentValue = convertToString(
        formData.value.afterFourHourTemperatureImgs as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 6小时后温度afterSixHourTemperature
    formDetail[13].componentValue = formData.value.afterSixHourTemperature;
    // 6小时后温度图片afterSixHourTemperatureImgs
    if (formData.value.afterSixHourTemperatureImgs.length) {
      formDetail[14].componentValue = convertToString(
        formData.value.afterSixHourTemperatureImgs as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 纠正措施jiuZhenChuoShi
    formDetail[15].componentValue = formData.value.jiuZhenChuoShi;
    formDetail[15].options.filter((item) => {
      if (splitName(item.optionTitle) === formData.value.jiuZhenChuoShi) {
        item.selected = true;
      }
    });
    //填报人姓名
    formDetail[16].componentValue = formData.value.tianBaoRenXinMing;
    // 其他数据
    const submitTable = ref<submitTableData>({
      formDetail: formDetail,
      reportingFormOperateId: reportingFormOperateId,
      status: 1,
      unionMenuId: '8286263252886290432',
    });

    return submitTable.value;
  };
  return {
    createTable,
    tableData,
    reportingFormOperateId,
    submitNewTable,
  };
};
const { createTable, submitNewTable, tableData, reportingFormOperateId } =
  table();
// 根据id展示数据
const showDataById = async (id: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await showTableById(id);

  if (res.msg === 'success') {
    // 冷却日期 date
    formData.value.date = res.data.formDetail[0].componentValue;
    // 餐段chanDuan
    res.data.formDetail[1].options.filter((item) => {
      if (item.selected) {
        formData.value.chanDuan = splitName(item.optionTitle);
      }
    });
    // 食物名称foodName
    formData.value.foodName = res.data.formDetail[2].componentValue;
    //开始时间selectedTime
    formData.value.selectedTime = res.data.formDetail[3].componentValue;
    // 开始温度startTemperature
    formData.value.startTemperature = res.data.formDetail[4].componentValue;
    // 开始温度图片startTemperatureImgs
    if (res.data.formDetail[5].tfiles) {
      formData.value.startTemperatureImgs = [];
      res.data.formDetail[5].tfiles.map((item) => {
        formData.value.startTemperatureImgs.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    // 1小时后温度afterOneHourTemperature
    formData.value.afterOneHourTemperature =
      res.data.formDetail[6].componentValue;
    // 1小时后温度图片afterOneHourTemperatureImgs
    if (res.data.formDetail[7].tfiles) {
      formData.value.afterOneHourTemperatureImgs = [];
      res.data.formDetail[7].tfiles.map((item) => {
        formData.value.afterOneHourTemperatureImgs.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    // 2小时后温度afterTwoHourTemperature
    formData.value.afterTwoHourTemperature =
      res.data.formDetail[8].componentValue;
    // 2小时后温度图片afterTwoHourTemperatureImgs
    if (res.data.formDetail[9].tfiles) {
      formData.value.afterTwoHourTemperatureImgs = [];
      res.data.formDetail[9].tfiles.map((item) => {
        formData.value.afterTwoHourTemperatureImgs.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    //2小时后纠正措施
    res.data.formDetail[10].options.filter((item) => {
      if (item.selected) {
        formData.value.towJiuZhenChuoShi = splitName(item.optionTitle);
      }
    });
    // 4小时后温度afterFourHourTemperature
    formData.value.afterFourHourTemperature =
      res.data.formDetail[11].componentValue;
    // 4小时后温度图片afterFourHourTemperatureImgs
    if (res.data.formDetail[12].tfiles) {
      formData.value.afterFourHourTemperatureImgs = [];
      res.data.formDetail[12].tfiles.map((item) => {
        formData.value.afterFourHourTemperatureImgs.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    // 6小时后温度afterSixHourTemperature
    formData.value.afterSixHourTemperature =
      res.data.formDetail[13].componentValue;
    // 6小时后温度图片afterSixHourTemperatureImgs
    if (res.data.formDetail[14].tfiles) {
      formData.value.afterSixHourTemperatureImgs = [];
      res.data.formDetail[14].tfiles.map((item) => {
        formData.value.afterSixHourTemperatureImgs.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    // 纠正措施jiuZhenChuoShi
    res.data.formDetail[15].options.filter((item) => {
      if (item.selected) {
        formData.value.jiuZhenChuoShi = splitName(item.optionTitle);
      }
    });
    //填报人姓名
    if (res.data.formDetail[16]) {
      formData.value.tianBaoRenXinMing = res.data.formDetail[16].componentValue;
    }

    // 评语
    reviewOpinion.value = (
      res.data as returnSubmitData
    ).handleOption.reviewOpinion;
  }
  uni.hideLoading();
};
onLoad(async () => {
  // 判断提交按钮是否等于newTable，
  // 等于newTable则执行创建表格
  if (props.value === 'newTable') {
    createTable();
  } else if (props.id) {
    showDataById(props.id);
    submitBtnName.value = '审批';
    isEdit.value = true;
  }
});
// 提交
const submitForm = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        // 等于newTable则执行提交表格
        if (props.value === 'newTable') {
          submitTable(
            submitNewTable(reportingFormOperateId.value, tableData.value),
          ).then((res) => {
            if (res.msg === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        } else if (props.id) {
          // 有id意味查看详情
          const data = ref<RequestMenuIdList>({
            id: props.id,
          });
          submitMenuIdList(data.value, reviewOpinion.value).then((res) => {
            if (res.data === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 加载配置
const showFormData = (data: any) => {
  compareLoadData(formData.value, data);
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
